package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.OmcLongRangeServiceOrderMapper;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.constant.*;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.dto.longRangeServiceOrder.*;
import com.csun.cmny.provider.model.dto.service.ServiceOrderOperationDto;
import com.csun.cmny.provider.model.vo.longRangeServiceOrder.LongRangeServiceOrderCommentVo;
import com.csun.cmny.provider.model.vo.longRangeServiceOrder.LongRangeServiceOrderVo;
import com.csun.cmny.provider.pojo.Oldman;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.JPushService;
import com.csun.cmny.provider.utils.SerialNumberUtil;
import com.csun.cmny.util.PublicUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class OmcLongRangeServiceOrderServiceImpl extends BaseService<OmcLongRangeServiceOrder> implements OmcLongRangeServiceOrderService {

    @Resource
    private OmcLongRangeServiceOrderMapper rangeServiceOrderMapper;

    @Resource
    private OmcSpecialistService specialistService;

    @Resource
    private OmcLongRangeServiceOrderCommentService commentService;

    @Resource
    private SerialNumberUtil serialNumberUtil;

    @Resource
    private OmcMerchandiseService merchandiseService;

    @Resource
    private OmcLongRangeServiceOrderMapper longRangeServiceOrderMapper;

    @Resource
    private OldmanService oldmanService;

    @Resource
    private JPushService jpushService;

    @Resource
    private CmnyMessageSource cmnyMessageSource;

    @Resource
    private OmcSuperviseLongRangeServiceService superviseLongRangeServiceService;

    @Resource
    private OmcVideoLongRangeServiceService videoLongRangeServiceService;

    @Override
    public Long videoPlaceAnOrder(LongRangeServiceOrderDto longRangeServiceOrderDto, LoginAuthDto loginAuthDto) {

        //老人是否存在
        Oldman oldman = new Oldman();
        oldman.setOldmanId(longRangeServiceOrderDto.getOlamanId().intValue());
        Oldman old = oldmanService.selectByOld(oldman);
        if (PublicUtil.isEmpty(old)){
            throw new OmcBizException(ErrorCodeEnum.OMC10031017);
        }

        //专家是否存在
        OmcSpecialist specialist = specialistService.selectByKey(longRangeServiceOrderDto.getSpecialistId());
        if (PublicUtil.isEmpty(specialist)){
            throw new OmcBizException(ErrorCodeEnum.OMC10032036);
        }

        OmcLongRangeServiceOrder omcLongRangeServiceOrder = new OmcLongRangeServiceOrder();

        BeanUtils.copyProperties(longRangeServiceOrderDto,omcLongRangeServiceOrder);

        omcLongRangeServiceOrder.setTotal(specialist.getVideoPrice());
        omcLongRangeServiceOrder.setOrderType(LongRangeServiceOrderTypeConstant.REMOTESUPERVISION);
        omcLongRangeServiceOrder.setOrderStatus(LongRangeServiceOrderStatusConstant.TOBECONFIRMED);
        omcLongRangeServiceOrder.setOperator(loginAuthDto.getUserName());
        omcLongRangeServiceOrder.setUserId(loginAuthDto.getUserId());
        omcLongRangeServiceOrder.setGroupId(old.getHomeId().longValue());
        omcLongRangeServiceOrder.setOrderNo(serialNumberUtil.getSerialNumberString());
        omcLongRangeServiceOrder.setRoyalties(specialist.getVideoRoyalty());

        longRangeServiceOrderMapper.insertSelective(omcLongRangeServiceOrder);

        return omcLongRangeServiceOrder.getId();
    }

    @Override
    public Long consultPlaceAnOrder(LongRangeServiceOrderDto longRangeServiceOrderDto, LoginAuthDto loginAuthDto) {

        //老人是否存在
        Oldman oldman = new Oldman();
        oldman.setOldmanId(longRangeServiceOrderDto.getOlamanId().intValue());
        Oldman old = oldmanService.selectByOld(oldman);
        if (PublicUtil.isEmpty(old)){
            throw new OmcBizException(ErrorCodeEnum.OMC10031017);
        }

        //专家是否存在
        OmcSpecialist specialist = specialistService.selectByKey(longRangeServiceOrderDto.getSpecialistId());
        if (PublicUtil.isEmpty(specialist)){
            throw new OmcBizException(ErrorCodeEnum.OMC10032036);
        }


        OmcLongRangeServiceOrder omcLongRangeServiceOrder = new OmcLongRangeServiceOrder();

        BeanUtils.copyProperties(longRangeServiceOrderDto,omcLongRangeServiceOrder);

        omcLongRangeServiceOrder.setTotal(specialist.getConsultPrice());
        omcLongRangeServiceOrder.setOrderType(LongRangeServiceOrderTypeConstant.CONSULT);
        omcLongRangeServiceOrder.setOrderStatus(LongRangeServiceOrderStatusConstant.PLACEDANORDER);
        omcLongRangeServiceOrder.setOperator(loginAuthDto.getUserName());
        omcLongRangeServiceOrder.setUserId(loginAuthDto.getUserId());
        omcLongRangeServiceOrder.setGroupId(old.getHomeId().longValue());
        omcLongRangeServiceOrder.setOrderNo(serialNumberUtil.getSerialNumberString());
        omcLongRangeServiceOrder.setRoyalties(specialist.getConsultRoyalty());

        longRangeServiceOrderMapper.insertSelective(omcLongRangeServiceOrder);
        return omcLongRangeServiceOrder.getId();
    }

    @Override
    public List<LongRangeServiceOrderVo> selectLongRangeServiceOrder(LongRangeServiceOrderSelectDto longRangeServiceOrderSelectDto) {
        List<LongRangeServiceOrderVo> longRangeServiceOrderVos = rangeServiceOrderMapper.selectLongRangeServiceOrder(longRangeServiceOrderSelectDto);

        for (LongRangeServiceOrderVo longRangeServiceOrderVo : longRangeServiceOrderVos) {

            //查看批注
            List<LongRangeServiceOrderCommentVo>commentVos=commentService.selectCommentsByOrderId(longRangeServiceOrderVo.getId());

            longRangeServiceOrderVo.setCommentVos(commentVos);

            //计算剩余到期时间
            if (longRangeServiceOrderVo.getOrderType()!=LongRangeServiceOrderTypeConstant.CONSULT){
                if (longRangeServiceOrderVo.getOrderStatus()==LongRangeServiceOrderStatusConstant.ALREADYIDENTIFIED){
                    Calendar enterTime = Calendar.getInstance();
                    enterTime.setTime(longRangeServiceOrderVo.getEnretTime());
                    enterTime.add(Calendar.MONTH,longRangeServiceOrderVo.getNumbers());
                    long expireTime = enterTime.getTime().getTime();
                    long theTime = new Date().getTime();

                    long days = (expireTime - theTime) / (1000 * 60 * 60 * 24);

                    //订单剩余时间
                    longRangeServiceOrderVo.setValidDays((int) days);
                    //订单截至日期
                    longRangeServiceOrderVo.setOverTime(enterTime.getTime());
                }
            }

            if (longRangeServiceOrderVo.getOrderType()==LongRangeServiceOrderTypeConstant.REMOTESUPERVISION){
                //写入视频订单服务集合
                List<OmcVideoLongRangeService> videoLongRangeServices = videoLongRangeServiceService.selectVideoByOrderId(longRangeServiceOrderVo.getId());
                longRangeServiceOrderVo.setVideoServices(videoLongRangeServices);
            }


            if (longRangeServiceOrderVo.getOrderType()==LongRangeServiceOrderTypeConstant.SUPERVISE){
                //写入远测监测服务集合
                List<OmcSuperviseLongRangeService> superviseLongRangeServices = superviseLongRangeServiceService.selectSuperviseByOrderId(longRangeServiceOrderVo.getId());
                longRangeServiceOrderVo.setSuperviseServises(superviseLongRangeServices);
            }

            //计算远程监测专家提成
           /*

            if (longRangeServiceOrderVo.getOrderType()==LongRangeServiceOrderTypeConstant.CONSULT){
                longRangeServiceOrderVo.setRoyalties(longRangeServiceOrderVo.getConsultRoyalty());
            }

            if (longRangeServiceOrderVo.getOrderType()==LongRangeServiceOrderTypeConstant.REMOTESUPERVISION){
                List<OmcVideoLongRangeService> videoLongRangeServices = videoLongRangeServiceService.selectVideoByOrderId(longRangeServiceOrderVo.getId());
                longRangeServiceOrderVo.setVideoServices(videoLongRangeServices);
                longRangeServiceOrderVo.setRoyalties(longRangeServiceOrderVo.getVideoRoyalty());
            }*/
        }
        return longRangeServiceOrderVos;
    }

    @Override
    public int video(OmcLongRangeServiceOrder omcLongRangeServiceOrder,LoginAuthDto loginAuthDto) {

        OmcSpecialist specialist = specialistService.selectByKey(omcLongRangeServiceOrder.getSpecialistId());

        Oldman oldman = new Oldman();
        oldman.setOldmanId(omcLongRangeServiceOrder.getOlamanId().intValue());
        Oldman old = oldmanService.selectByOld(oldman);

        //新增视频服务
        OmcVideoLongRangeService omcVideoLongRangeService = new OmcVideoLongRangeService();
        omcVideoLongRangeService.setOrderId(omcLongRangeServiceOrder.getId());
        omcVideoLongRangeService.setInitiateTime(new Date());
        omcVideoLongRangeService.setVideoStatus(LongRangeServiceOrderStatusConstant.INITIATE_VIDEO);
        videoLongRangeServiceService.save(omcVideoLongRangeService);


        String message = JSONObject.fromObject(omcVideoLongRangeService).toString();

        List<String> tagList = Lists.newArrayList();

        tagList.add(DmcConstant.USER_PREFIX+specialist.getStaffUserId());


        // 视频消息推送给专家
        jpushService.sendToDoctor(cmnyMessageSource.getMessage("longRangeServiceOrder.video.start", null),
                VideoStatusConstant.VIDEO_START,
                old.getOldName(),
                message,
                tagList);




        //新增批注
        OmcLongRangeServiceOrderComment orderComment = new OmcLongRangeServiceOrderComment();
        orderComment.setLongRangeServiceOrderId(omcLongRangeServiceOrder.getId());
        orderComment.setUserId(loginAuthDto.getUserName());
        orderComment.setMessage(ServiceOrderCommentMessageConstant.LAUNCH_VIDEO);
        int save = commentService.save(orderComment);


        return omcVideoLongRangeService.getId().intValue();
    }

    @Override
    public int connect(OmcVideoLongRangeService omcVideoLongRangeService,OmcLongRangeServiceOrder omcLongRangeServiceOrder, LoginAuthDto loginAuthDto) {

        //当月剩余视频次数更新
        omcLongRangeServiceOrder.setResidueNumber(omcLongRangeServiceOrder.getResidueNumber()-1);

        if (omcLongRangeServiceOrder.getResidueNumber()<1){
            omcLongRangeServiceOrder.setOrderStatus(LongRangeServiceOrderStatusConstant.NUMBEROFCOMPLETE);
        }

        //更改订单状态
        int update = update(omcLongRangeServiceOrder);

        //更改视频服务状态
        omcVideoLongRangeService.setVideoStatus(LongRangeServiceOrderStatusConstant.CONNECT_VIDEO);
        omcVideoLongRangeService.setConnectTime(new Date());
        videoLongRangeServiceService.update(omcVideoLongRangeService);

        //新增批注
        OmcLongRangeServiceOrderComment orderComment = new OmcLongRangeServiceOrderComment();
        orderComment.setLongRangeServiceOrderId(omcLongRangeServiceOrder.getId());
        orderComment.setUserId(loginAuthDto.getUserName());
        orderComment.setMessage(ServiceOrderCommentMessageConstant.GET_THROUGH_VIDEO);
        int save = commentService.save(orderComment);


        //视频接通消息推送给用户
        OmcSpecialist specialist = specialistService.selectByKey(omcLongRangeServiceOrder.getSpecialistId());

        String message = JSONObject.fromObject(omcLongRangeServiceOrder).toString();

        List<String> tagList = Lists.newArrayList();

        tagList.add(DmcConstant.USER_PREFIX+omcLongRangeServiceOrder.getUserId());

        jpushService.sendToFamily(cmnyMessageSource.getMessage("longRangeServiceOrder.video.connect", null),
                VideoStatusConstant.VIDEO_CONNECT,
                specialist.getSpecialistName(),
                message,
                tagList);

        return update;
    }

    @Override
    public int finish(OmcVideoLongRangeService videoLongRangeService,OmcLongRangeServiceOrder omcLongRangeServiceOrder, LoginAuthDto loginAuthDto) {

        //视频结束消息推送给专家和用户
        OmcSpecialist specialist = specialistService.selectByKey(omcLongRangeServiceOrder.getSpecialistId());

        Oldman oldman = new Oldman();
        oldman.setOldmanId(omcLongRangeServiceOrder.getOlamanId().intValue());
        Oldman old = oldmanService.selectByOld(oldman);

        String message = JSONObject.fromObject(videoLongRangeService).toString();

        //推送给用户
        List<String> tagListUser = Lists.newArrayList();
        tagListUser.add(DmcConstant.USER_PREFIX+omcLongRangeServiceOrder.getUserId());


        jpushService.sendToFamily(cmnyMessageSource.getMessage("longRangeServiceOrder.video.end", null),
                VideoStatusConstant.VIDEO_END,
                specialist.getSpecialistName(),
                message,
                tagListUser);

        //推送给专家
        List<String> tagListSpecialist = Lists.newArrayList();
        tagListSpecialist.add(DmcConstant.USER_PREFIX+specialist.getStaffUserId());


        jpushService.sendToDoctor(cmnyMessageSource.getMessage("longRangeServiceOrder.video.end", null),
                VideoStatusConstant.VIDEO_END,
                old.getOldName(),
                message,
                tagListSpecialist);


        //更改视频服务状态
        videoLongRangeService.setVideoStatus(LongRangeServiceOrderStatusConstant.END_VIDEO);
        videoLongRangeService.setEndTime(new Date());
        videoLongRangeServiceService.update(videoLongRangeService);

        //新增批注
        OmcLongRangeServiceOrderComment orderComment = new OmcLongRangeServiceOrderComment();
        orderComment.setLongRangeServiceOrderId(omcLongRangeServiceOrder.getId());
        orderComment.setUserId(loginAuthDto.getUserName());
        orderComment.setMessage(ServiceOrderCommentMessageConstant.FINISH_VIDEO);
        int save = commentService.save(orderComment);

        return save;
    }

    @Override
    public Long superviseAnOrder(LongRangeServiceOrderSuperviseDto longRangeServiceOrderSuperviseDto, LoginAuthDto loginAuthDto) {
        //老人是否存在
        Oldman oldman = new Oldman();
        oldman.setOldmanId(longRangeServiceOrderSuperviseDto.getOlamanId().intValue());
        Oldman old = oldmanService.selectByOld(oldman);
        if (PublicUtil.isEmpty(old)){
            throw new OmcBizException(ErrorCodeEnum.OMC10031017);
        }

        OmcMerchandise merchandise = merchandiseService.selectByKey(longRangeServiceOrderSuperviseDto.getMerchandiseId());
        if (PublicUtil.isEmpty(merchandise)){
            throw new OmcBizException(ErrorCodeEnum.MDC10021017);
        }


        OmcLongRangeServiceOrder omcLongRangeServiceOrder = new OmcLongRangeServiceOrder();

        BeanUtils.copyProperties(longRangeServiceOrderSuperviseDto,omcLongRangeServiceOrder);

        omcLongRangeServiceOrder.setTotal(merchandise.getUnitPrice());
        omcLongRangeServiceOrder.setResidueNumber(merchandise.getServiceNumber());
        omcLongRangeServiceOrder.setEnretTime(new Date());
        omcLongRangeServiceOrder.setOrderType(LongRangeServiceOrderTypeConstant.SUPERVISE);
        omcLongRangeServiceOrder.setOrderStatus(LongRangeServiceOrderStatusConstant.TOBECONFIRMED);
        omcLongRangeServiceOrder.setOperator(loginAuthDto.getUserName());
        omcLongRangeServiceOrder.setUserId(loginAuthDto.getUserId());
        omcLongRangeServiceOrder.setGroupId(old.getHomeId().longValue());
        omcLongRangeServiceOrder.setOrderNo(serialNumberUtil.getSerialNumberString());
        omcLongRangeServiceOrder.setServiceAddress(longRangeServiceOrderSuperviseDto.getServiceAddress());

        //计算远程监测专家提成
        BigDecimal unitPrice = merchandise.getUnitPrice();
        Integer serviceFee = merchandise.getServiceFee();
        BigDecimal fee = new BigDecimal(serviceFee);
        omcLongRangeServiceOrder.setRoyalties(unitPrice.multiply(fee).divide(new BigDecimal(100)));

        longRangeServiceOrderMapper.insertSelective(omcLongRangeServiceOrder);

        return omcLongRangeServiceOrder.getId();
    }

    @Override
    public int superviseEnter(LongRangeServiceOrderSuperviseEnterDto longRangeServiceOrderSuperviseEnterDto, LoginAuthDto loginAuthDto) {

        OmcLongRangeServiceOrder omcLongRangeServiceOrder = new OmcLongRangeServiceOrder();
        omcLongRangeServiceOrder.setId(longRangeServiceOrderSuperviseEnterDto.getOrderId());
        omcLongRangeServiceOrder.setSpecialistId(longRangeServiceOrderSuperviseEnterDto.getSpecialistId());
        omcLongRangeServiceOrder.setOrderStatus(LongRangeServiceOrderStatusConstant.ALREADYIDENTIFIED);
        return update(omcLongRangeServiceOrder);
    }

    @Override
    public int theDoorMonitoring(ServiceOrderOperationDto serviceOrderOperationDto,OmcLongRangeServiceOrder omcLongRangeServiceOrder, LoginAuthDto loginAuthDto) {
        //监测次数更新
        omcLongRangeServiceOrder.setResidueNumber(omcLongRangeServiceOrder.getResidueNumber()-1);

        //次数已经用尽
        if (omcLongRangeServiceOrder.getResidueNumber()<1){
            omcLongRangeServiceOrder.setOrderStatus(LongRangeServiceOrderStatusConstant.NUMBEROFCOMPLETE);
        }

        //更新订单详情
        int update = update(omcLongRangeServiceOrder);

        //新增远程监测服务
        OmcSuperviseLongRangeService superviseLongRangeService = new OmcSuperviseLongRangeService();
        superviseLongRangeService.setOrderId(omcLongRangeServiceOrder.getId());
        superviseLongRangeService.setVisitTime(new Date());
        superviseLongRangeService.setSuperviseStatus(LongRangeServiceOrderStatusConstant.VISIT_SUPERVISE);
        superviseLongRangeServiceService.save(superviseLongRangeService);

        //新增批注
        OmcLongRangeServiceOrderComment orderComment = new OmcLongRangeServiceOrderComment();
        orderComment.setLongRangeServiceOrderId(omcLongRangeServiceOrder.getId());
        orderComment.setUserId(loginAuthDto.getUserName());
        orderComment.setMessage(ServiceOrderCommentMessageConstant.THE_DOOR_MONITORING);
        orderComment.setRemark(serviceOrderOperationDto.getRemark());
        orderComment.setImgCode(serviceOrderOperationDto.getImgCode());
        int save = commentService.save(orderComment);

        return update;
    }

    @Override
    public int pay(Long id) {
        OmcLongRangeServiceOrder longRangeServiceOrder = selectByKey(id);
        if (PublicUtil.isEmpty(longRangeServiceOrder)){
            throw new OmcBizException(ErrorCodeEnum.OMC10032005);
        }
        if (longRangeServiceOrder.getIsPayed()!= ServiceOrderConstant.ORDER_UNPAYED){
            throw new OmcBizException(ErrorCodeEnum.OMC10032035);
        }

        longRangeServiceOrder.setIsPayed(ServiceOrderConstant.ORDER_PAYED);
        return update(longRangeServiceOrder);
    }

    @Override
    public int doorMonitoringLeave(OmcSuperviseLongRangeService omcSuperviseLongRangeService, ServiceOrderOperationLeaveDto serviceOrderOperationLeaveDto, OmcLongRangeServiceOrder omcLongRangeServiceOrder, LoginAuthDto loginAuthDto) {

        //更新远程监测服务
        omcSuperviseLongRangeService.setLeaveTime(new Date());
        omcSuperviseLongRangeService.setSuperviseStatus(LongRangeServiceOrderStatusConstant.LEAVE_SUPERVISE);
        superviseLongRangeServiceService.update(omcSuperviseLongRangeService);

        //新增批注
        OmcLongRangeServiceOrderComment orderComment = new OmcLongRangeServiceOrderComment();
        orderComment.setLongRangeServiceOrderId(omcLongRangeServiceOrder.getId());
        orderComment.setUserId(loginAuthDto.getUserName());
        orderComment.setMessage(ServiceOrderCommentMessageConstant.DOOR_MONITORING_LEAVE);
        orderComment.setRemark(serviceOrderOperationLeaveDto.getRemark());
        orderComment.setImgCode(serviceOrderOperationLeaveDto.getImgCode());

        int save = commentService.save(orderComment);
        return save;
    }
}
